<!DOCTYPE html>
<html lang="zh" class="no-js">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="description" content="book">
<meta name="generator" content="Paradox, paradox-material-theme=0.6.0, mkdocs-material=3.0.3">

<meta name="lang:clipboard.copy" content="Copy to clipboard">
<meta name="lang:clipboard.copied" content="Copied to clipboard">
<meta name="lang:search.language" content="">
<meta name="lang:search.pipeline.stopwords" content="true">
<meta name="lang:search.pipeline.trimmer" content="true">
<meta name="lang:search.result.none" content="No matching documents">
<meta name="lang:search.result.one" content="1 matching document">
<meta name="lang:search.result.other" content="# matching documents">
<meta name="lang:search.tokenizer" content="[\s\-]+">


<meta name="description" content="book">
<link rel="shortcut icon" href="../assets/images/favicon.png">
<title>Scalatest · Scala Web 开发——基于Akka HTTP</title>
<link rel="stylesheet" href="../assets/stylesheets/application.451f80e5.css">
<link rel="stylesheet" href="../assets/stylesheets/application-palette.22915126.css">
<meta name="theme-color" content="#009688" />
<link rel="stylesheet" href="../lib/material__tabs/dist/mdc.tabs.min.css">
<link rel="stylesheet" href="../lib/prettify/prettify.css">
<script src="../assets/javascripts/modernizr.1aa3b519.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,400i,700|Roboto+Mono">
<style>
body,input{font-family:"Roboto","Helvetica Neue",Helvetica,Arial,sans-serif}
code,kbd,pre{font-family:"Roboto Mono","Courier New",Courier,monospace}
</style>
<link rel="stylesheet" href="../assets/fonts/font-awesome.css">
<link rel="stylesheet" href="../assets/fonts/material-icons.css">
<link rel="stylesheet" href="../assets/stylesheets/paradox-material-theme.css">
</head>
<body
data-md-color-primary="teal"
data-md-color-accent="indigo"
>
<input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer" autocomplete="off">
<input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search" autocomplete="off">
<label class="md-overlay" data-md-component="overlay" for="__drawer"></label>
<header class="md-header" data-md-component="header">
<nav class="md-header-nav md-grid">
<div class="md-flex">
<div class="md-flex__cell md-flex__cell--shrink">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-header-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label>
</div>
<div class="md-flex__cell md-flex__cell--stretch">
<div class="md-flex__ellipsis md-header-nav__title" data-md-component="title">
<span class="md-header-nav__topic">
Scala Web 开发——基于Akka HTTP
</span>
<span class="md-header-nav__topic">
Scalatest
</span>
</div>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<label class="md-icon md-icon--search md-header-nav__button" for="__search"></label>
<div class="md-search" data-md-component="search" role="dialog">
<label class="md-search__overlay" for="__search"></label>
<div class="md-search__inner" role="search">
<form class="md-search__form" name="search">
<input type="text" class="md-search__input" name="query" placeholder="Search" autocapitalize="off" autocorrect="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active">
<label class="md-icon md-search__icon" for="__search"></label>
<button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">&#xE5CD;</button>
</form>
<div class="md-search__output">
<div class="md-search__scrollwrap" data-md-scrollfix>
<div class="md-search-result" data-md-component="result">
<div class="md-search-result__meta">
Type to start searching
</div>
<ol class="md-search-result__list"></ol>
</div>
</div>
</div>
</div>
</div>

</div>
<div class="md-flex__cell md-flex__cell--shrink">
<div class="md-header-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
</div>
</div>
</nav>
</header>

<div class="md-container">
<main class="md-main">
<div class="md-main__inner md-grid" data-md-component="container">
<div class="md-sidebar md-sidebar--primary" data-md-component="navigation">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--primary" data-md-level="0" style="visibility: hidden">
<label class="md-nav__title md-nav__title--site" for="drawer">
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP" class="md-nav__button md-logo">
<span class="md-nav__button md-logo">
<i class="md-icon">local_library</i>
</a>
<a href="../index.html" title="Scala Web 开发——基于Akka HTTP">
Scala Web 开发——基于Akka HTTP
</a>
</label>
<div class="md-nav__source">
<a href="https://github.com/yangbajing/scala-web-development"
title="Go to repository"
class="md-source"
data-md-source="github">
<div class="md-source__icon">
<i class="fa fa-github"></i>
</div>
<div class="md-source__repository">
yangbajing/scala-web-development
</div>
</a>

</div>
<ul>
  <li><a href="../preface.html" class="page">前言</a></li>
  <li><a href="../env/index.html" class="page">Scala 环境配置</a>
  <ul>
    <li><a href="../env/env.1.html" class="page">Sbt</a></li>
    <li><a href="../env/env.2.html" class="page">IDE开发工具</a></li>
    <li><a href="../env/env.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../scala/index.html" class="page">Scala 语言基础</a>
  <ul>
    <li><a href="../scala/scala.0.html" class="page">REPL</a></li>
    <li><a href="../scala/scala.1.html" class="page">你好，Scala</a></li>
    <li><a href="../scala/scala.2.html" class="page">Scala基础</a></li>
    <li><a href="../scala/scala.3.html" class="page">流程和函数</a></li>
    <li><a href="../scala/scala.4.html" class="page">集合</a></li>
    <li><a href="../scala/scala.5.html" class="page">class和object</a></li>
    <li><a href="../scala/scala.6.html" class="page">函数式</a></li>
    <li><a href="../scala/scala.7.html" class="page">Trait</a></li>
    <li><a href="../scala/scala.8.html" class="page">并发</a></li>
    <li><a href="../scala/scala.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../basic/index.html" class="page">Akka HTTP 基础</a>
  <ul>
    <li><a href="../basic/basic.0.html" class="page">Akka HTTP 基础</a></li>
    <li><a href="../basic/basic.1.html" class="page">Web 工作方式</a></li>
    <li><a href="../basic/basic.2.html" class="page">使用 Akka Http 搭建一个简单的 Web 服务</a></li>
    <li><a href="../basic/basic.3.html" class="page">Akka HTTP 的通用抽象</a></li>
    <li><a href="../basic/basic.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../server-api/index.html" class="page">服务端API</a>
  <ul>
    <li><a href="../server-api/work.html" class="page">Akka HTTP 如何使得 Web 工作</a></li>
    <li><a href="../server-api/advanced.html" class="page">高级服务端 API</a></li>
  </ul></li>
  <li><a href="../routing-dsl/index.html" class="page">路由DSL</a>
  <ul>
    <li><a href="../routing-dsl/route.html" class="page">Route 路由</a></li>
    <li><a href="../routing-dsl/directive.html" class="page">Directive 指令</a></li>
    <li><a href="../routing-dsl/custom-directive.html" class="page">自定义指令</a></li>
    <li><a href="../routing-dsl/rejections.html" class="page">拒绝 rejections</a></li>
    <li><a href="../routing-dsl/exception.html" class="page">异常处理</a></li>
    <li><a href="../routing-dsl/file-upload.html" class="page">实战：大文件断点上传、下载和秒传</a></li>
  </ul></li>
  <li><a href="../directives/index.html" class="page">常用指令</a>
  <ul>
    <li><a href="../directives/path.html" class="page">PathDirectives（路径指令）</a></li>
    <li><a href="../directives/method.html" class="page">directives/method.html</a></li>
    <li><a href="../directives/parameter_form.html" class="page">directives/parameter_form.html</a></li>
    <li><a href="../directives/marshalling.html" class="page">directives/marshalling.html</a></li>
    <li><a href="../directives/file.html" class="page">directives/file.html</a></li>
    <li><a href="../directives/cookie.html" class="page">directives/cookie.html</a></li>
  </ul></li>
  <li><a href="../data/index.html" class="page">数据</a>
  <ul>
    <li><a href="../data/data.0.html" class="page">数据</a></li>
    <li><a href="../data/data.1.html" class="page">JSON</a></li>
    <li><a href="../data/data.ant-design-pro.html" class="page">实战：为Ant Design Pro提供后端接口</a></li>
    <li><a href="../data/data.kryo.html" class="page">Kryo</a></li>
    <li><a href="../data/data.2.html" class="page">Protobuf</a></li>
    <li><a href="../data/data.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../test/index.html" class="page">测试</a>
  <ul>
    <li><a href="../test/test.0.html" class="page">测试</a></li>
    <li><a href="../test/test.1.html" class="active page">Scalatest</a></li>
    <li><a href="../test/test.2.html" class="page">测试异步代码</a></li>
    <li><a href="../test/test.3.html" class="page">端到端测试Route</a></li>
    <li><a href="../test/test.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../actor/index.html" class="page">Akka Actor</a>
  <ul>
    <li><a href="../actor/actor.html" class="page">Akka Typed Actor</a></li>
    <li><a href="../actor/actor-test.html" class="page">Akka Actor 测试</a></li>
    <li><a href="../actor/actor.z.html" class="page">Actor小结</a></li>
  </ul></li>
  <li><a href="../oauth/index.html" class="page">实战：实现OAuth 2服务</a>
  <ul>
    <li><a href="../oauth/oauth.0.html" class="page">实战：OAuth 2 服务</a></li>
    <li><a href="../oauth/oauth.1.html" class="page">OAuth 2简介</a></li>
    <li><a href="../oauth/oauth.2.html" class="page">OAuth 2接口设计</a></li>
    <li><a href="../oauth/oauth.3.html" class="page">OAuth 2服务实现</a></li>
    <li><a href="../oauth/oauth.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../database/index.html" class="page">访问数据库</a>
  <ul>
    <li><a href="../database/database.0.html" class="page">访问数据库</a></li>
    <li><a href="../database/database.1.html" class="page">使用 JDBC 访问 PostgreSQL</a></li>
    <li><a href="../database/database.2.html" class="page">使用 Slick 访问数据库</a></li>
    <li><a href="../database/database.3.html" class="page">访问 Cassandra 数据库</a></li>
    <li><a href="../database/database.4.html" class="page">访问 Redis</a></li>
    <li><a href="../database/database.5.html" class="page">访问 Elasticsearch</a></li>
    <li><a href="../database/database.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../engineering/index.html" class="page">工程化</a>
  <ul>
    <li><a href="../engineering/swagger.html" class="page">使用Swagger编写API文档</a></li>
    <li><a href="../engineering/guice.html" class="page">使用Guice管理类依赖</a></li>
  </ul></li>
  <li><a href="../grpc/index.html" class="page">Akka gRPC</a>
  <ul>
    <li><a href="../grpc/grpc.html" class="page">gRPC服务</a></li>
    <li><a href="../grpc/build-tool.html" class="page">构建工具</a></li>
    <li><a href="../grpc/deployment.html" class="page">部署</a></li>
    <li><a href="../grpc/grpc.z.html" class="page">小结</a></li>
  </ul></li>
  <li><a href="../config-discovery/index.html" class="page">实战：配置管理、服务发现系统</a></li>
  <li><a href="../appendix/index.html" class="page">附录</a>
  <ul>
    <li><a href="../appendix/appendix.0.html" class="page">参考资料</a></li>
    <li><a href="../appendix/appendix.1.html" class="page">专业术语</a></li>
    <li><a href="../appendix/appendix.2.html" class="page">词汇表</a></li>
  </ul></li>
  <li><a href="../donate.html" class="page">赞助</a></li>
</ul>
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../test/test.1.html#scalatest" class="header">Scalatest</a>
  <ul>
    <li><a href="../test/test.1.html#安装-scalatest" class="header">安装 ScalaTest</a></li>
    <li><a href="../test/test.1.html#第一个测试用例" class="header">第一个测试用例</a></li>
    <li><a href="../test/test.1.html#使用-matchers" class="header">使用 Matchers</a></li>
    <li><a href="../test/test.1.html#optionvalues" class="header">OptionValues</a></li>
    <li><a href="../test/test.1.html#scalafutures" class="header">ScalaFutures</a></li>
    <li><a href="../test/test.1.html#mock" class="header">Mock</a></li>
  </ul></li>
</ul>
</nav>

</nav>
<ul style="display: none">
<li class="md-nav__item md-version" id="project.version">
<label class="md-nav__link" for="__version">
<i class="md-icon" title="Version">label_outline</i> 1.0.0
</label>
</li>
</ul>
</div>
</div>
</div>
<div class="md-sidebar md-sidebar--secondary" data-md-component="toc">
<div class="md-sidebar__scrollwrap">
<div class="md-sidebar__inner">
<nav class="md-nav md-nav--secondary">
<label class="md-nav__title" for="__toc">Table of contents</label>
<ul>
  <li><a href="../test/test.1.html#scalatest" class="header">Scalatest</a>
  <ul>
    <li><a href="../test/test.1.html#安装-scalatest" class="header">安装 ScalaTest</a></li>
    <li><a href="../test/test.1.html#第一个测试用例" class="header">第一个测试用例</a></li>
    <li><a href="../test/test.1.html#使用-matchers" class="header">使用 Matchers</a></li>
    <li><a href="../test/test.1.html#optionvalues" class="header">OptionValues</a></li>
    <li><a href="../test/test.1.html#scalafutures" class="header">ScalaFutures</a></li>
    <li><a href="../test/test.1.html#mock" class="header">Mock</a></li>
  </ul></li>
</ul>
</nav>

</div>
</div>
</div>
<div class="md-content">
<article class="md-content__inner md-typeset">
<div class="md-content__searchable">
<h1><a href="#scalatest" name="scalatest" class="anchor"><span class="anchor-link"></span></a>Scalatest</h1>
<p>ScalaTest通过简单、清晰的测试和可执行的规范来提高团队的生产力，同时改进代码和沟通效率。</p>
<p>ScalaTest是Scala生态系统中最灵活、最流行的测试工具。支持测试：Scala、Scala.js（Javascript）和Java代码。可与JUnit、TestNG、Ant、Maven、sbt、ScalaCheck、JMock、EasyMock、Mockito、ScalaMock、Selenium、Eclipse、Netbeans、Intellij、VSCode等工具集成使用。ScalaTest可使Scala、Scala.js或者Java项目的测试更容易，拥有更高的生产力水平。</p>
<p>为了最大化生产力，ScalaTest内建扩展点并支持多种测试方式。我们可以选择最适合我们团队经验和文化的测试风格。有以下风格可供选择：</p>
<ul>
  <li>FunSuite：来自xUnit。</li>
  <li>FlatSpec：另一个来自xUnit。</li>
  <li>FunSpec：来自Ruby&rsquo;s RSpec的BDD测试风格。</li>
  <li>WordSpec：来自specs、specs2，适合训练有素的团队来定义严格的测试规范。也是Akka、Playframework等推荐的风格。</li>
  <li>FreeSpec：适合有经验的团队。</li>
  <li>PropSpec：适合追求完美的团队，需要前置测试条件定义。</li>
  <li>FeatureSpec：主要用于验收测试。</li>
  <li>RefSpec（JVM only）：需要定义一个特殊的测试函数，通过测试函数字面量来代码测试功能。</li>
</ul>
<h2><a href="#安装-scalatest" name="安装-scalatest" class="anchor"><span class="anchor-link"></span></a>安装 ScalaTest</h2>
<p>ScalaTest的安装、使用很简单，可以直接在命令行使用，如：</p>
<pre><code>$ scalac -cp scalatest-app_2.12-3.0.5.jar ExampleSpec.scala
</code></pre>
<p>也可以和sbt集成使用。对sbt不了解的读者可以先看：<a href="http://www.yangbajing.me/scala-web-development/env.1.html">http://www.yangbajing.me/scala-web-development/env.1.html</a> 来快速的学习sbt的使用方法。</p>
<p>在sbt中添加ScalaTest支持非常简单，在构建配置文件（一般是build.sbt）中添加库依赖即可。</p>
<pre><code>libraryDependencies += &quot;org.scalatest&quot; %% &quot;scalatest&quot; % &quot;3.0.5&quot; % &quot;test&quot;
</code></pre>
<p>之后重启sbt或在sbt命令行控制台里输入：<code>reload</code>以使其生效。</p>
<h2><a href="#第一个测试用例" name="第一个测试用例" class="anchor"><span class="anchor-link"></span></a>第一个测试用例</h2>
<pre><code>import scala.collection.mutable
import org.scalatest._

class FirstTest extends WordSpec with Matchers {
  &quot;A Stack&quot; should {
    &quot;pop values in last-in-first-out order&quot; in {
      val stack = mutable.Stack.empty[Int]
      stack.push(1)
      stack.push(2)
      stack.pop() shouldBe 2
      stack.pop() shouldBe 1
    }
    
    &quot;throw NoSuchElementException if an empty stack is popped&quot; in {
      val emptyStack = mutable.Stack.empty[Int]
      assertThrows[NoSuchElementException] {
        emptyStack.pop()
      }
    }
  }
}
</code></pre>
<p>运行测试有两种方式：</p>
<ol>
  <li>使用<code>test</code>命令运行所有测试</li>
  <li>使用<code>testOnly</code>命令运行单个测试。</li>
</ol>
<p>在sbt中输入<code>testOnly firstFirstTest</code>运行刚写好的第一个测试，结果如下：</p>
<pre><code>[IJ]scalatest &gt; testOnly first.FirstTest
[info] Compiling 1 Scala source to /opt/workspace/scala-applications/scalatest/target/scala-2.12/test-classes ...
[info] Done compiling.
[info] FirstTest:
[info] A Stack
[info] - should pop values in last-in-first-out order
[info] - should throw NoSuchElementException if an empty stack is popped
[info] Run completed in 344 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
[success] Total time: 2 s, completed 2018-8-2 18:29:14
</code></pre>
<h2><a href="#使用-matchers" name="使用-matchers" class="anchor"><span class="anchor-link"></span></a>使用 Matchers</h2>
<p>除了默认的断言函数，如：<code>assert</code>、<code>assertResult</code>、<code>assertThrows</code>等，ScalaTest还提供了更好用的 <strong>Matchers</strong>。**Matchers** 具有以下特性：</p>
<ul>
  <li>基于表达式断言的DSL，如：<code>stack.pop() shouldBe 2</code>。更易读，以人类语言的方式来编写测试断言。</li>
  <li>丰富的断言类型，支持更直观的断言表达式，如：<code>&quot;abbccxxx&quot; should startWith regex (&quot;a(b*)(c*)&quot; withGroups (&quot;bb&quot;, &quot;cc&quot;))</code>。</li>
</ul>
<p>只需要在测试类混入 <code>Matchers</code> 特质，就可以使用 ScalaTest 提供的强大的 Matchers 特性。</p>
<h2><a href="#optionvalues" name="optionvalues" class="anchor"><span class="anchor-link"></span></a>OptionValues</h2>
<p>OptionValues特质提供了一个隐式转换，将一个 <code>value</code> 方法添加到 <code>Option[T]</code> 类型上。若 Option 是有定义的，则 <code>value</code> 方法将返回值，就和调用 <code>.get</code> 一样；若没有，则抛出 <code>TestFailedException</code> 异常，而不是调用 <code>get</code> 方法时抛出的 <code>NoSuchElementException</code> 异常。同时，ScalaTest会输出更友好的错误显示：**The Option on which value was invoked was not defined.**，而不是输出一大堆的错误异常栈而打乱正常的测试输出。</p>
<p><strong>使用<code>.value</code></strong></p>
<pre><code>[info] FirstTest:
[info] option
[info] - should value *** FAILED ***
[info]   The Option on which value was invoked was not defined. (FirstTest.scala:30)
[info] Run completed in 418 milliseconds.
[info] Total number of tests run: 3
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 1, canceled 0, ignored 0, pending 0
[info] *** 1 TEST FAILED ***
[error] Failed tests:
[error] 	first.FirstTest
[error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful
</code></pre>
<p><strong>使用<code>.get</code></strong></p>
<pre><code>[info] FirstTest:
[info] option
[info] - should value *** FAILED ***
[info]   java.util.NoSuchElementException: None.get
[info]   at scala.None$.get(Option.scala:349)
[info]   at scala.None$.get(Option.scala:347)
[info]   at first.FirstTest.$anonfun$new$6(FirstTest.scala:31)
[info]   at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
[info]   at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
[info]   at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
[info]   at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
[info]   at org.scalatest.Transformer.apply(Transformer.scala:22)
[info]   at org.scalatest.Transformer.apply(Transformer.scala:20)
[info]   at org.scalatest.WordSpecLike$$anon$1.apply(WordSpecLike.scala:1078)
[info]   ...
[info] Run completed in 211 milliseconds.
[info] Total number of tests run: 3
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 2, failed 1, canceled 0, ignored 0, pending 0
[info] *** 1 TEST FAILED ***
[error] Failed tests:
[error] 	first.FirstTest
[error] (Test / testOnly) sbt.TestsFailedException: Tests unsuccessful
</code></pre>
<h2><a href="#scalafutures" name="scalafutures" class="anchor"><span class="anchor-link"></span></a>ScalaFutures</h2>
<p>ScalaTest支持对异步代码进行阻塞测试。提供了隐式方法 <code>futureValue</code> 来从 <code>Future[T]</code> 中阻塞获取结果。</p>
<pre><code>override implicit def patienceConfig = PatienceConfig(Span(60, Seconds), Span(50, Millis))

  &quot;future&quot; should {
    &quot;await result === 3&quot; in {
      import scala.concurrent.ExecutionContext.Implicits.global
      val f = Future{
        Thread.sleep(1000)
        3
      }
      val result = f.futureValue
      result shouldBe 3
    }
  }
</code></pre>
<p>上面代码的运行效果如下：</p>
<pre><code>[info] FirstTest:
[info] future
[info] - should await result === 3
[info] Run completed in 1 second, 169 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
</code></pre>
<h2><a href="#mock" name="mock" class="anchor"><span class="anchor-link"></span></a>Mock</h2>
<p>ScalaTest为以下4种Mock提供了原生的支持：</p>
<ol>
  <li><a href="http://www.scalamock.org/">ScalaMock</a></li>
  <li>EasyMock</li>
  <li>JMock</li>
  <li>Mockito</li>
</ol>
<p>这里先简单介绍下 <strong>ScalaMock</strong>。</p>
<p>ScalaMock是由 Paul Butcher 编写的一个原生的开源Scala Mocking框架，允许模拟对象和函数。ScalaMock支持3种不同的模拟风格：</p>
<ul>
  <li>函数模拟（Function mocks）</li>
  <li>代理（动态）模拟（Proxy (dynamic) mocks）</li>
  <li>生成类型安全模拟（Generated (type-safe) mocks）</li>
</ul>
<p><strong>函数模拟</strong></p>
<pre><code>  &quot;scalamock&quot; should {
    &quot;function mock&quot; in {
      val m = mockFunction[Int, String]
      m expects 42 returning &quot;Forty two&quot;
      m(42) shouldBe &quot;Forty two&quot;
    }
  }
</code></pre>
<p>这里我们模拟了一个函数 <code>m</code>，它接受一个Int参数并返回一个字符串值。这里看到，我们并没有实际定义这样一个函数，而是使用 <code>m expects 42 returning &quot;Forty two&quot;</code> 声明了这个模拟期待一个输入值：42，并返回结果字符串：<code>Forty row</code>。执行这个测试，运行效果如下：</p>
<pre><code>[info] FirstTest:
[info] scalamock
[info] - should function mock
[info] Run completed in 211 milliseconds.
[info] Total number of tests run: 1
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
</code></pre>
</div>
<div>
<a href="https://github.com/yangbajing/scala-web-development/tree/master/book/src/main/paradox/test/test.1.md" title="Edit this page" class="md-source-file md-edit">
Edit this page
</a>
</div>
<div class="print-only">
<span class="md-source-file md-version">
1.0.0
</span>
</div>
</article>
</div>
</div>
</main>
<footer class="md-footer">
<div class="md-footer-nav">
<nav class="md-footer-nav__inner md-grid">
<a href="../test/test.0.html" title="测试" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev">
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-back md-footer-nav__button"></i>
</div>
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Previous
</span>
测试
</span>
</div>
</a>
<a href="../test/test.2.html" title="测试异步代码" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next">
<div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title">
<span class="md-flex__ellipsis">
<span class="md-footer-nav__direction">
Next
</span>
测试异步代码
</span>
</div>
<div class="md-flex__cell md-flex__cell--shrink">
<i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i>
</div>
</a>
</nav>
</div>
<div class="md-footer-meta md-typeset">
<div class="md-footer-meta__inner md-grid">
<div class="md-footer-copyright">
Powered by
<a href="https://github.com/lightbend/paradox">Paradox</a>
and
<a href="https://jonas.github.io/paradox-material-theme/">Paradox Material Theme</a>

</div>
<div class="md-footer-social">
<a href="https://github.com/yangbajing" class="md-footer-social__link fa fa-github"></a><a href="https://weibo.com/yangbajing" class="md-footer-social__link fa fa-globe"></a><a href="https://www.yangbajing.me/" class="md-footer-social__link fa fa-globe"></a>
</div>

</div>
</div>
</footer>

</div>
<script src="../assets/javascripts/application.583bbe55.js"></script>
<script src="../assets/javascripts/paradox-material-theme.js"></script>
<script>app.initialize({version:"0.17",url:{base:"../."}})</script>
<script type="text/javascript" src="../lib/prettify/prettify.js"></script>
<script type="text/javascript" src="../lib/prettify/lang-scala.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function(event) {
window.prettyPrint && prettyPrint();
});
</script>
</body>
</html>
